import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:study_flutter/yzhg/dartTools/YEventBusUtil.dart';
import 'package:study_flutter/yzhg/function/eventbus/YEventBusBeanDemo.dart';

class YEventBusDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("EventBus"),
      ),
      body: Column(
        children: <Widget>[YLeftEventPage(), YRightEventPage()],
      ),
    );
  }
}

class YLeftEventPage extends StatefulWidget {
  @override
  _YLeftEventPageState createState() => _YLeftEventPageState();
}

class _YLeftEventPageState extends State<YLeftEventPage> {
  int position = 1;

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      height: ScreenUtil().setHeight(500),
      decoration: BoxDecoration(
          border: Border(bottom: BorderSide(width: 2, color: Colors.pink))),
      child: Center(
        child: RaisedButton(
          onPressed: () {
            //发送通知
            YEventBusUtil.getInstance().fire(YEventBusBeanDemo("请接受我的膝盖",position));
            position++;
          },
          child: Text("发送一个String字符串"),
        ),
      ),
    );
  }
}

class YRightEventPage extends StatefulWidget {
  @override
  _YRightEventPageState createState() => _YRightEventPageState();
}

class _YRightEventPageState extends State<YRightEventPage> {
  String test = "接受上面传来的数据";

  StreamSubscription<YEventBusBeanDemo> _event;

  @override
  void initState() {
    super.initState();
    _event = YEventBusUtil.getInstance().on<YEventBusBeanDemo>().listen((data) {
      setState(() {
        test = "${data.test} 次数: ${data.position}";
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      height: ScreenUtil().setHeight(500),
      decoration: BoxDecoration(
          border:
              Border(bottom: BorderSide(width: 2, color: Colors.blueAccent))),
      child: Text(
        test,
        style: TextStyle(fontSize: ScreenUtil().setSp(26), color: Colors.black),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    //移除EventBus监听
    _event.cancel();
  }
}
